package edu.uba.fcen.estimacion.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import edu.uba.fcen.estimacion.estimacion.Means;

public class QueryWordsDB {
	private Connection connection;

	public QueryWordsDB(String pathToCSV) {
		DataBaseBuilderWords words = new DataBaseBuilderWords(pathToCSV);
		this.connection = words.create(Integer.MAX_VALUE);
	}
	
	public QueryWordsDB(String pathToCSV, int topK) {
		DataBaseBuilderWords words = new DataBaseBuilderWords(pathToCSV);
		this.connection = words.create(topK);
	}

	public Means means(String word) {
		Means means = new Means();
		String query = "SELECT * FROM words WHERE palabra = 'WORD'";
//		if (this.topK != Integer.MAX_VALUE) {
////			query = "SELECT * FROM (SELECT * FROM words AS w ORDER BY w.id ASC LIMIT " + this.topK + ") AS ww WHERE ww.palabra = 'WORD'";
//			query = "SELECT * FROM (SELECT TOP " + this.topK + " * FROM words AS w ORDER BY w.id ASC) AS ww WHERE ww.palabra = 'WORD'";
//		}
		try {
			Statement statement = this.connection.createStatement();
			String queryReplaced = query.replaceAll("WORD", word);
			ResultSet rs = statement.executeQuery(queryReplaced);
			if (rs.next()) {
				means = new Means(rs.getDouble(3), rs.getDouble(4),
						rs.getDouble(5), rs.getDouble(6), rs.getDouble(7),
						rs.getDouble(8));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return means;
	}

	public void close() {
		try {
			this.connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
